<template>
  <div class="pets-form">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>{{ isEdit ? '编辑宠物' : '添加宠物' }}</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编号" prop="userId">
              <el-input v-model.number="form.userId" placeholder="请输入客户编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宠物名字" prop="petName">
              <el-input v-model="form.petName" placeholder="请输入宠物名字" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品种" prop="petBreed">
              <el-input v-model="form.petBreed" placeholder="请输入品种" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="petType">
              <el-input v-model="form.petType" placeholder="请输入类型（猫/狗/其他）" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="petGender">
              <el-select v-model="form.petGender" placeholder="请选择性别">
                <el-option label="公" value="MALE" />
                <el-option label="母" value="FEMALE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="petBirth">
              <el-date-picker
                v-model="form.petBirth"
                type="date"
                placeholder="选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毛色" prop="petColor">
              <el-input v-model="form.petColor" placeholder="请输入毛色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="petWeight">
              <el-input-number
                v-model="form.petWeight"
                :precision="2"
                :step="0.1"
                placeholder="请输入体重"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否绝育" prop="petNeuter">
              <el-switch v-model="form.petNeuter" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 新增图片上传区域 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="宠物图片" prop="photoUrl">
              <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/upload"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
              >
                <img v-if="form.photoUrl" :src="form.photoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">点击上传图片（建议尺寸：300×300）</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="重要备注" prop="petNotes">
              <el-input
                v-model="form.petNotes"
                type="textarea"
                :rows="3"
                placeholder="请输入重要备注"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源" prop="source">
              <el-input v-model="form.source" placeholder="请输入来源（购买/领养/其他）" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, UploadProps } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { petsApi } from '@/api'
import type { Pets } from '@/types'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 性别映射表（显示文本到存储值的映射）
const genderMap = {
  '公': 'MALE',
  '母': 'FEMALE'
}

// 反向映射表（存储值到显示文本的映射）
const reverseGenderMap = {
  'MALE': '公',
  'FEMALE': '母',
  // 兼容数字类型存储（如果后端使用数字）
  '1': '公',
  '0': '母'
}

// 表单数据
const form = reactive<Pets>({
  petId: undefined,
  userId: 0,
  petName: '',
  petType: '',
  petBreed: '',
  petBirth: '',
  petGender: 'MALE', // 默认显示为"公"
  petWeight: 0,
  petColor: '',
  petNeuter: 0,
  source: '',
  photoUrl: '',
  petNotes: ''
})

// 表单验证规则
const rules: FormRules = {
  userId: [
    { required: true, message: '请输入客户编号', trigger: 'blur' }
  ],
  petName: [
    { required: true, message: '请输入宠物名字', trigger: 'blur' }
  ],
  petType: [
    { required: true, message: '请输入类型（猫/狗/其他）', trigger: 'blur' }
  ],
  petBreed: [
    { required: true, message: '请输入品种', trigger: 'blur' }
  ],
  petBirth: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  petGender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  petWeight: [
    { required: true, message: '请输入体重', trigger: 'blur' }
  ],
  petColor: [
    { required: true, message: '请输入毛色', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请输入来源（购买/领养/其他）', trigger: 'blur' }
  ]
}

// 获取宠物详情
const fetchPetDetail = async (id: number) => {
  try {
    const response = await petsApi.getById(id)
    if (response.code === 200) {
      const data = { ...response.data };
      
      // 处理日期字符串
      if (data.petBirth && typeof data.petBirth === 'string') {
        const dateParts = data.petBirth.split('-');
        if (dateParts.length === 3) {
          data.petBirth = new Date(
            parseInt(dateParts[0]),
            parseInt(dateParts[1]) - 1,
            parseInt(dateParts[2])
          );
        } else if (data.petBirth.includes('T')) {
          const date = new Date(data.petBirth);
          data.petBirth = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        }
      }
      
      // 处理性别显示（关键修改点）
      if (data.petGender !== undefined) {
        data.petGender = reverseGenderMap[data.petGender] || data.petGender;
      }
      
      Object.assign(form, data);
    } else {
      ElMessage.error(response.message || '获取宠物详情失败')
    }
  } catch (error) {
    console.error('获取宠物详情失败:', error)
    ElMessage.error('获取宠物详情失败')
  }
}

// 图片上传处理
const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 200) {
    form.photoUrl = response.data; // 假设后端返回 { code:200, data: "图片URL" }
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.message || '图片上传失败');
  }
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

const buildPetPayload = (form: any) => {
  // 确保所有字段正确映射
  const payload = {
    petId: form.petId,
    userId: form.userId,
    petName: form.petName,
    petBreed: form.petBreed,
    petType: form.petType,
    // 处理性别提交（关键修改点）
    petGender: genderMap[form.petGender] || form.petGender,
    petColor: form.petColor,
    petWeight: form.petWeight,
    petNeuter: form.petNeuter ? 1 : 0,
    petNotes: form.petNotes,
    source: form.source,
    photoUrl: form.photoUrl // 添加图片URL
  };
  
  // 修复日期格式化
  if (form.petBirth instanceof Date) {
    const year = form.petBirth.getFullYear();
    const month = String(form.petBirth.getMonth() + 1).padStart(2, '0');
    const day = String(form.petBirth.getDate()).padStart(2, '0');
    payload.petBirth = `${year}-${month}-${day}`;
  } else if (typeof form.petBirth === 'string') {
    payload.petBirth = form.petBirth;
  } else {
    payload.petBirth = '';
  }
  
  return payload;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    
    const payload = buildPetPayload(form)
    console.log('提交数据:', payload)  // 调试用
    
    const response = isEdit.value 
      ? await petsApi.update(payload)
      : await petsApi.add(payload)
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      
      if (window.history.length > 1) {
        router.go(-1)
      } else {
        router.push('/pets/list')
      }
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  if (window.history.length > 1) {
    router.go(-1);
  } else {
    router.push('/base/pets');
  }
}

onMounted(() => {
  if (isEdit.value) {
    const petId = Number(route.params.id)
    if (petId) {
      fetchPetDetail(petId)
    }
  }
})
</script>

<style scoped>
.pets-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

/* 图片上传样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}
</style>